package me.boot.db.mybatis.interceptor.datascope;

import cn.hutool.core.lang.Assert;
import me.boot.common.context.ContextUtil;
import me.boot.common.data.enums.DataScopeType;
import me.boot.common.data.model.DataPermissionInfo;
import me.boot.common.data.model.UserInfo;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.statement.select.SelectItem;

import java.util.List;

/**
 * @Description:
 * @author: Sylar
 * @date: 2021年11月25日 2:56 下午
 */
public class DefaultDataScopeHandler implements DataScopeHandler {

    @Override
    public boolean needDataScope(String mappedStatementId) {
        return getDataPermission(mappedStatementId) != null;
    }

    @Override
    public List<SelectItem> getSelectItems(String mappedStatementId, List<SelectItem> selectItems) {
        DataPermissionInfo dataPermissionInfo = getDataPermission(mappedStatementId);
        Assert.notNull(dataPermissionInfo);
        DataScopeUtil.fieldFilter(selectItems, dataPermissionInfo);
        return selectItems;
    }

    @Override
    public Expression getSqlSegment(String mappedStatementId, Expression where) {
        DataPermissionInfo dataPermissionInfo = getDataPermission(mappedStatementId);
        Assert.notNull(dataPermissionInfo);
        DataScopeType scopeType = dataPermissionInfo.getDataScopeType();
        UserInfo user = getUser();
        Assert.notNull(user);

        switch (scopeType) {
            case SELF:
                return DataScopeUtil.byUser(user.getUserId());
            case THIS_LEVEL:
                return DataScopeUtil.byOrg(user.getDepartmentIds());
            case THIS_LEVEL_AND_BRANCH:
                return DataScopeUtil.byOrg(user.getNestedDepartmentIds());
            default:
                return null;
        }
    }

    DataPermissionInfo getDataPermission(String mappedStatementId) {
        UserInfo user = getUser();
        if (user != null && user.getDataPermissionInfoMap() != null) {
            return user.getDataPermissionInfoMap().get(mappedStatementId);
        }
        return null;
    }

    UserInfo getUser() {
        return ContextUtil.getUser();
    }

}
